<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>watch和computed</title>
    <script src="./lib/vue-2.6.12.js"></script>
    <script src="./lib/vue-router-3.5.1.js"></script>
</head>

<body>
    <div id="app">
        <!-- <input type="text" v-model="firstname" @keyup="updateName"> +
        <input type="text" v-model="lastname" @keyup="updateName"> + -->
        <input type="text" v-model="firstname"> +
        <input type="text" v-model="lastname"> =
        <input type="text" v-model="fullname"> : 
        <input type="text" v-bind:value="calcName">
        <hr>
        <router-link to="/login">登录</router-link>
        <router-link to="/register">注册</router-link>
        <router-view></router-view>
    </div>

    <script>
        const Login = {
            template: '<div><h2>登录组件</h2></div>'
        }
        const Register = {
            template: '<div><h2>注册组件</h2></div>'
        }

        const router = new VueRouter({
            routes: [
                { path: '/', redirect: '/login' },
                { path: '/login', component: Login },
                { path: '/register', component: Register }
            ]
        })

        let vm = new Vue({
            el: '#app',
            data: {
                firstname: '',
                lastname: '',
                fullname: ''
            },
            methods: {
                // 直接响应事件，更简单些
                // updateName() {
                //     this.fullname = this.firstname + '-' + this.lastname;
                // }
            },
            watch: {
                // 当需要在数据变化时执行异步或开销较大的操作时，这个方式是最有用的，
                // 比如路由变化，获取服务器数据等
                firstname: function (newVal, oldVal) {
                    this.fullname = newVal + '-' + this.lastname;
                },
                lastname: function () {
                    this.fullname = this.firstname + '-' + this.lastname;
                },
                '$route.path': function (newVal, oldVal) {
                    if (newVal === '/login') {
                        console.log('欢迎进入登录页面！')
                    } else if (newVal === '/register') {
                        console.log('欢迎进入注册页面！')
                    }
                }
            },
            router,
            computed: {
                // 计算属性是基于它们的响应式依赖进行缓存的，只在依赖发生改变时它们才会重新求值
                calcName: function () {
                    return this.firstname + '-' + this.lastname;
                }
            }
        })
    </script>
</body>

</html>